package com.zhengxyou.androiddemo.appBasics.configurationActivity;

import android.content.res.Configuration;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;

import com.zhengxyou.androiddemo.R;

/**
 * <a href="https://developer.android.google.cn/guide/topics/resources/runtime-changes?hl=zh-cn3">参考地址</a>
 * <pre>
 *
 *  处理运行时变更：
 *  1、在配置变更期间保留对象
 *      <p>
 *          会在销毁前调用 {@link AppCompatActivity#onSaveInstanceState(Bundle)}，在这个方法里面保存有关应用的数据
 *         <br>
 *              然后可以在 {@link AppCompatActivity#onCreate(Bundle)}或者 {@link AppCompatActivity#onRestoreInstanceState(Bundle)}里面恢复Activity的状态
 *      </p>
 *  2、自动处理配置变更
 *  <P>
 *      编辑配置清单文件中对应的Activity的 <code>android:configChanges</code>属性
 *      <br>
 *      当配置发生变化时,不会重启Activity，Activity会收到 {@link AppCompatActivity#onConfigurationChanged(Configuration)}方法的调用
 *  </P>
 *
 *
 * </pre>
 * <br>
 * 作用/接口:适应新的配置条件
 * <p>重启行为旨在通过利用与新设备配置匹配的备用资源自动重新加载您的应用，来帮助它适应新配置。</p>
 * <br>
 * 起因:
 * <p>
 * 有些设备配置在运行时发生变化。如屏幕方向，键盘收缩，语言变更
 * </P>
 * <br>
 * 流程：
 * <p>
 * 重启正在运行的Activity，先后调用 {@link AppCompatActivity#onDestroy()}和 {@link AppCompatActivity#onCreate(Bundle)}
 * </p>
 */
public class ConfigActivity extends AppCompatActivity {
    private RetainFragment retainFragment;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_config);

        FragmentManager fm = getSupportFragmentManager();
        retainFragment = (RetainFragment) fm.findFragmentByTag("data");

        if (retainFragment == null) {
            retainFragment = new RetainFragment();
            fm.beginTransaction().add(retainFragment, "data").commit();
            retainFragment.setData(new Object());
        }
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        retainFragment.setData(new Object());
    }
}
